'use strict'

const router =require('koa-router')();
const fs =require('fs');

function getRouterFiles(filePath){
    let tmpPth =__dirname || filePath;
    let files =fs.readdirSync(tmpPth);
    let routeFiles =files.filter(item=>{
        return item.endsWith('.js') && item !=='index.js';
    })
    return routeFiles;
}

function registerRoute(router,routeFiles){
    routeFiles.forEach(item => {
        let tmpPth =__dirname +'/' +item;
        let obj =require(tmpPth);
        for(let key in obj){
            let tmpArr =key.split(' ');
            let routeMethod =tmpArr[0];
            let routeUrl =tmpArr[1];
            let routeFun =obj[key];
            if(routeMethod ==='get'){
                router.get(routeUrl,routeFun);
            }else if(routeMethod ==='post'){
                router.post(routeUrl,routeFun);
            }else if(routeMethod ==='put'){
                router.put(routeUrl,routeFun);
            }else if(routeMethod ==='delete'){
                router.delete(routeUrl,routeFun);
            }else{
                console.log('程序有误');
            }
        }
    });
    return router.routes();
}

module.exports =function(){
    let routeFiles=getRouterFiles();
    let fn =registerRoute(router,routeFiles);
    return fn;
}